package tcdx.uap.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tcdx.uap.common.utils.Lutils;
import tcdx.uap.common.utils.MapUtils;
import tcdx.uap.mapper.BaseDBMapper;
import tcdx.uap.mapper.FlowableMapper;
import tcdx.uap.service.entities.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 参数配置 服务层实现
 * 
 * @author ruoyi
 */
@Service
public class FlowableService {

    @Autowired
    private FlowableMapper flowableMapper;

    /**
     * 部署流程
     */
//    public String deploy_flow(String flow_def_name, String flow_text) {
//        Deployment deploy = repositoryService.createDeployment()
//                .addString(flow_def_name, flow_text).name(flow_def_name).deploy();
//        return deploy.getId();
//    }

    /**
     * 删除部署的流程
     * 参数：流程id
     * 如果部署流程启动了，就不允许删除了
     */
//    public int delete_deployment(String deployment_id_) {
//        repositoryService.deleteDeployment(deployment_id_);
//        return 1;
//    }

    //获取流程基本信息
//    public Map<String, Object> get_deployment(String deployment_id) {
//        // 使用历史流程实例查询流程定义
//        Deployment deploy = processEngine.getRepositoryService()
//                .createDeploymentQuery()
//                .deploymentId(deployment_id)
//                .singleResult();
//        return MapUtils.G("name", deploy.getName(), "key", deploy.getKey());
//    }

//    //获取流程的xml数据
//    public String get_deployment_xml_by_id(String proc_def_id) {
//
//        InputStream in = processEngine.getRepositoryService().getProcessModel(proc_def_id);
//        // 获取流程定义的XML
//        String processDefinitionXml = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));
//        return processDefinitionXml;
//    }


    @Autowired
    BaseDBMapper baseDBMapper;

    @Autowired
    BaseDBService baseDBService;

    public List<Integer> gen_ids(int count) {
        List<Map> l = baseDBService.selectSql("select nextval('tcdx_datatable_id_seq') id,generate_series(1, " + count + ") num");
        return l.stream().map(o -> Integer.parseInt(o.get("id").toString())).collect(Collectors.toList());
    }

    @Transactional
    public void data_mode_create(Map userInfo, Map func, Map datatable, List<Map> form_list) {
        List<Integer> new_ids = gen_ids(form_list.size());
        Date now = new Date();
        for (int i = 0; i < form_list.size(); i++) {
            //单纯的插入数据到数据库
            Map form = form_list.get(i);
            form.put("id_", new_ids.get(i));
            //获取需要触发其他模块的字段信息
            form.put("assignee_", userInfo.get("user_name"));   //如果数据模式，则assignee_为接单人
            form.put("assignee_group_", userInfo.get("user_group"));
            form.put("complete_user_", userInfo.get("user_name"));  //如果数据模式，则complete_user_为创建人
            form.put("complete_group_", userInfo.get("user_group"));
            form.put("complete_time_", now);
            form.put("update_user_", userInfo.get("user_name"));
            form.put("update_group_", userInfo.get("user_group"));
            form.put("update_time_", now);
            form.put("form_id_", func.get("form_id"));
            baseDBService.insertMap(datatable.get("table_name").toString(), form);
//            datatable_update(userInfo, func, list, datatable, "data-create", now);

        }
    }


    @Transactional
    public void datatable_update(Map userInfo, Map func, Map row, Map<String,Object> form, Integer id, Map datatable, String action_type, UserAction action) {
        //获取表名
        String tn = datatable.get("table_name").toString();
        Integer table_id = (Integer)datatable.get("id");
        Map<String,Object> beforeData = new HashMap();
        //横向拓展字段
        if(row==null || row.size()==0) {
            row = baseDBService.selectEq(tn, Lutils.genMap("id_", id)).get(0);
            MapUtils.copy(row, beforeData);
        }
        //系统字段，通过系统获取
        //List<Map> sysFlowFields = tableColumns.stream().filter(o-> Lutils.nvl((String)o.get("field_content_from"),"").equals("system-flow")).collect(Collectors.toList());
        //将存入log的字段
        List<Object> logIds = new ArrayList<>();
        //填充用户操作等信息
        form.put("action_type_", action_type);
        form.put("update_user_", userInfo.get("user_name"));
        form.put("update_group_", userInfo.get("user_group"));
        form.put("update_time_", action.action_time);
        form.put("form_id_", func.get("form_id"));
        baseDBService.updateIn(tn, form, "id_", Lutils.genList(id));//------------------------update database
        //添加ids
        logIds.add(id);
        // 2、更新按实例同步的数据
        List<Map> tableColumns=null;
        List<Integer> syncIds = new ArrayList<>();
        Map<String, Object> syncForm = new HashMap<>();
        if (datatable.get("type").equals("flow")) {//如果是流程类型的数据表
            String proc_inst_id_ = (String)row.get("proc_inst_id_");
            tableColumns = baseDBService.selectEq("tcdx_datatable_columns", Lutils.genMap("table_id", table_id));
            /** 1、更新用于流程流转的变量 */
            //获取跟流程相关联的字段，选取关键字段存入流程，以免过多数据库插入，影响效率。
            List<Map> flowVarFields = null;
            if(datatable.get("type").equals("flow")){
                flowVarFields = baseDBService.selectEq("tcdx_flow_related_role", MapUtils.G("menu_id", datatable.get("menu_id")));
            }
            Map<String, Object> variables = new HashMap();
            flowVarFields.stream().filter(o -> form.containsKey(o.get("field"))).collect(Collectors.toList()).forEach(o -> {
                variables.put(o.get("field").toString(), form.get(o.get("field")));
            });
            if (variables.size() > 0) {
                //提取本地更新涉及的流程实例id集合
//                taskService.setVariables(proc_inst_id_, variables); //------------------------update database
            }
            /** 2、按实例同步字段 */
            //需要按实例同步修改的字段,找出需要同步的字段,按proc_inst_id_更新
            tableColumns.stream().filter(o -> Lutils.nvl(o.get("is_sync_inst"),false)&&form.containsKey(o.get("field")))
                    .collect(Collectors.toList()).forEach(o->{ syncForm.put(o.get("field").toString(), form.get(o.get("field"))); });
            //存入流程变量
            if (syncForm.size() > 0) {
                baseDBService.updateEq(tn, form, Lutils.genMap("proc_inst_id_", proc_inst_id_));
                syncIds=baseDBService.selectEq(tn, Lutils.genMap("proc_inst_id_", proc_inst_id_)).stream().map(o->(Integer)o.get("id_")).collect(Collectors.toList());
            }
        }
        //获取新添加的数据，插入日志表
        flowableMapper.copy_to_log(MapUtils.G("tn", tn, "ids", syncIds.size()>0?syncIds:logIds, "log_time_", action.action_time)); //------------------------update database

        //递归横向拓展 form
        ColumnRuleOperationStore columnRuleOperationStore = new ColumnRuleOperationStore();
        for(Map.Entry<String,Object> entry: form.entrySet()) {
            ColumnRuleOperation columnRuleOperation = new ColumnRuleOperation(
                    tn,
                    entry.getKey(),
                    "user-form",
                    entry.getValue(),
                    null, null);
            columnRuleOperation.addInIds(Lutils.genList(id));
            columnRuleOperationStore.addTableColumnRule(tn, columnRuleOperation);
        }
    }

    /**
     * 1、流程启动。执行启动动作，记录启动动作，并将启动后的任务实例保存至表格。
     * 2、

    @Transactional
    public void task_start(Map userInfo, Map func, Map datatable, List<Map> form_list){
        String tn =  datatable.get("table_name").toString();
        //获取跟流程相关联的字段，选取关键字段存入流程，以免过多数据库插入，影响效率
        List<Map> relatedCols = baseDBService.selectEq("tcdx_flow_related_role",  MapUtils.G("menu_id", datatable.get("menu_id")));
        //获取需要填入流程动作内容的字段
        List<Map> tableColumns = baseDBService.selectEq("tcdx_datatable_columns",Lutils.genMap("table_id", datatable.get("id")));
        //系统字段，通过系统获取
        List<Map> sysFields = tableColumns.stream().filter(o-> Lutils.nvl(o.get("is_system_value"),false)==true).collect(Collectors.toList());
        //需要按实例同步修改的字段
        List<Map> syncFields = tableColumns.stream().filter(o-> Lutils.nvl(o.get("is_sync_inst"),false)).collect(Collectors.toList());
        List<Integer> need_log_ids = new ArrayList<>();
        List<Integer> ids= gen_ids(form_list.size());
        need_log_ids.addAll(ids);
        for(int x=0;x<form_list.size();x++) {
            Map form = form_list.get(x);
            Map<String,Object> startForm = new HashMap(form);
            //取出流程相关的字段，提供给flowable
            Map<String, Object> relatedVariables = new HashMap();
            for (Map m : relatedCols)
                relatedVariables.put(m.get("related_col").toString(), form.get(m.get("related_col")));
            //启动流程
            ProcessInstance processInstance = runtimeService.startProcessInstanceById(datatable.get("proc_def_id_").toString(), relatedVariables);
            HistoricActivityInstance startAct = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).activityId("startEvent1").singleResult();
            //processInstance.
            //保存已经记录操作记录
            startForm.put("id_", ids.get(x));
            startForm.put("proc_inst_id_",   startAct.getProcessInstanceId());
            startForm.put("task_id_", startAct.getProcessInstanceId());
            startForm.put("task_name_", startAct.getActivityName()==null?"开始":startAct.getActivityName());
            startForm.put("task_def_key_", startAct.getActivityId());
            startForm.put("execution_id_",  startAct.getExecutionId());
            startForm.put("assignee_",       userInfo.get("user_name"));
            startForm.put("assignee_group_", userInfo.get("user_group"));
            startForm.put("complete_user_",   userInfo.get("user_name"));
            startForm.put("complete_group_",  userInfo.get("user_group"));
            startForm.put("complete_time_",  startAct.getEndTime());
            startForm.put("complete_type_", "task-start");
            startForm.put("form_id_", func.get("form_id"));
            startForm.put("is_done_", true);
            startForm.put("is_inst_user_new_complete_", true);
            startForm.put("is_inst_new_complete_", true);
            startForm.put("is_inst_ended_", false);
            startForm.put("prev_task_id_", null);
            startForm.put("prev_task_name_", null);
            startForm.put("prev_task_def_key_", null);
            startForm.put("parent_execution_id_", null);
            startForm.put("prev_deliver_staff_", null);
            startForm.put("prev_deliver_group_", null);
            startForm.put("prev_deliver_time_", null);
            startForm.put("prev_deliver_type_", null);
            startForm.put("operation_order_", 0);
            //补充系统字段
            for(Map f: sysFields){
                String act_id = f.get("related_act_id").toString();
                String act_prop = f.get("related_act_prop").toString();
                //当前环节 或 与指定环节相匹配
                if(act_id.equals("current_activity") || act_id.equals(startForm.get("task_def_key_"))){
                    String field = f.get("field").toString();
                    startForm.put(field, startForm.get(act_prop));
                }
            }
            baseDBService.insertMap(tn, startForm);
            //找出需要同步的字段
            Map syncData = new HashMap();
            syncFields.stream().filter(o->startForm.containsKey(o.get("field"))).collect(Collectors.toList()).forEach(o->{
                syncData.put(o.get("field").toString(), startForm.get(o.get("field")));
            });
            //添加待办信息
            List<Task> taskList = taskService.createTaskQuery().processInstanceId( processInstance.getProcessInstanceId() ).list();
            List<Integer> task_ids_= gen_ids(taskList.size());
            need_log_ids.addAll(task_ids_);
            for (int i = 0; i < taskList.size(); i++) {
                Task task = taskList.get(i);
                //设置接单人
                Map assigneeInfo = new HashMap<>(userInfo);
                task.setAssignee(assigneeInfo.get("user_name").toString());
                //保存到数据库
                Map taskForm = new HashMap(startForm);
                taskForm.put("id_", task_ids_.get(i));
                taskForm.put("proc_inst_id_", task.getProcessInstanceId());
                taskForm.put("task_id_", task.getId());
                taskForm.put("task_name_", task.getName());
                taskForm.put("task_def_key_", task.getTaskDefinitionKey());
                taskForm.put("execution_id_",   task.getExecutionId());
                taskForm.put("assignee_",       assigneeInfo.get("user_name"));
                taskForm.put("assignee_group_", assigneeInfo.get("user_group"));
                taskForm.put("complete_user_",   null);
                taskForm.put("complete_group_",  null);
                taskForm.put("complete_time_", null);
                taskForm.put("complete_type_", null);
                taskForm.put("form_id_", null);
                taskForm.put("is_done_", false);
                taskForm.put("is_inst_user_new_complete_", false);
                taskForm.put("is_inst_new_complete_", false);
                taskForm.put("is_inst_ended_", false);
                taskForm.put("prev_task_id_", startAct.getProcessInstanceId());
                taskForm.put("prev_task_name_", startAct.getActivityName()==null?"开始":startAct.getActivityName());
                taskForm.put("prev_task_def_key_", startAct.getActivityId());
                taskForm.put("parent_execution_id_", startAct.getExecutionId());
                taskForm.put("prev_deliver_staff_", userInfo.get("user_name"));
                taskForm.put("prev_deliver_group_", userInfo.get("user_group"));
                taskForm.put("prev_deliver_time_", startAct.getEndTime());
                taskForm.put("prev_deliver_type_", "task-start");
                taskForm.put("operation_order_", 1);
                //补充系统字段
                for(Map f: sysFields){
                    String act_id = f.get("related_act_id").toString();
                    String act_prop = f.get("related_act_prop").toString();
                    //当前环节 或 与指定环节相匹配
                    if(act_id.equals("current_activity") || act_id.equals( taskForm.get("task_def_key_"))){
                        String field = f.get("field").toString();
                        taskForm.put(field, taskForm.get(act_prop));
                    }
                }
                baseDBService.insertMap(tn, taskForm);
                //更新同步字段
                syncFields.stream().filter(o->taskForm.containsKey(o.get("field"))).collect(Collectors.toList()).forEach(o->{
                    syncData.put(o.get("field").toString(), taskForm.get(o.get("field")));
                });
            }
            //更新该实例的待办用户任务数
            flowableMapper.update_todo_tasks(Lutils.genMap("tn", tn, "proc_inst_id_", startAct.getProcessInstanceId()));
            //实例数据同步
            if(!syncData.isEmpty())
                baseDBService.updateEq(tn, syncData, Lutils.genMap("proc_inst_id_", startAct.getProcessInstanceId()));
        }
        //批量保存日志，获取新添加的数据，插入日志表
        flowableMapper.copy_to_log(MapUtils.G( "tn", tn, "ids", need_log_ids,"log_time_", new Date()));
    }


    @Transactional
    public void task_complete(Map userInfo,Map func, List<Object> ids, Map datatable, Map form) throws Exception{
        String tn =  datatable.get("table_name").toString();
        //获取跟流程相关联的字段，选取关键字段存入流程，以免过多数据库插入，影响效率
        List<Map> relatedCols = baseDBService.selectEq("tcdx_flow_related_role", MapUtils.G("menu_id", datatable.get("menu_id")));
        //获取需要填入流程动作内容的字段
        List<Map> tableColumns = baseDBService.selectEq("tcdx_datatable_columns",Lutils.genList("id","field","related_act_id","related_act_prop","is_system_value","is_sync_inst"),Lutils.genMap("table_id", datatable.get("id")));
        //系统字段，通过系统获取
        List<Map> sysFields = tableColumns.stream().filter(o-> Lutils.nvl(o.get("is_system_value"),false)).collect(Collectors.toList());
        //需要按实例同步修改的字段
        List<Map> syncFields = tableColumns.stream().filter(o-> Lutils.nvl(o.get("is_sync_inst"),false)).collect(Collectors.toList());
        //每一行的数据
        List<Map> row_list = baseDBService.selectIn( tn, "id_", ids);
        List<Object> need_log_ids = new ArrayList<>();
        for(Map r: row_list) { //处理一条任务。
            Map curRow = new HashMap(r);
            Map completeForm = new HashMap(form);
            String task_id_ = (String) curRow.get("task_id_");
            String proc_inst_id_ = (String) curRow.get("proc_inst_id_");
            String task_def_key_ = (String) curRow.get("task_def_key_");
            int operation_order_ = Lutils.nvl( curRow.get("operation_order_"),0);
            //取流程流转判断所需要用到的流程变量.如果form中有，优先从form中取，表单中的数据，更新到row中
            form.forEach((key, value) -> curRow.put(key,value));
            Map<String, Object> relatedVariables = new HashMap<>();
            for (Map m : relatedCols) {
                relatedVariables.put( m.get("related_col").toString(),  curRow.get(m.get("related_col")));
            }
            // 流程：处理任务
            taskService.complete( task_id_, relatedVariables);
            //同一用户处理过的实例，的最新标记
            baseDBService.updateEq(tn,Lutils.genMap("is_inst_user_new_complete_", false) ,Lutils.genMap("proc_inst_id_",proc_inst_id_,"complete_user_", userInfo.get("user_name")));
            baseDBService.updateEq(tn,Lutils.genMap("is_inst_new_complete_", false) ,Lutils.genMap("proc_inst_id_",proc_inst_id_ ));
            //取当前完成的任务
            HistoricTaskInstance completedTask = historyService.createHistoricTaskInstanceQuery().taskId(task_id_).singleResult();
            completeForm.put("complete_user_",  userInfo.get("user_name"));
            completeForm.put("complete_group_", userInfo.get("user_group"));
            completeForm.put("complete_time_", completedTask.getEndTime());
            completeForm.put("complete_type_", "task-complete");
            completeForm.put("is_done_", true);
            completeForm.put("form_id_", func.get("form_id"));
            completeForm.put("is_inst_user_new_complete_", true);
            completeForm.put("is_inst_new_complete_", true);
            //判断任务是否到达结束状态
            HistoricActivityInstance endEvent = historyService.createHistoricActivityInstanceQuery().processInstanceId(proc_inst_id_).activityType("endEvent").singleResult();

            //将completeForm的完成动作数据，更新到row中
            completeForm.forEach((key, value) -> curRow.put(key, value));
            //填充系统字段
//            List<String>completeFields=Lutils.genList("complete_user_","complete_group_","complete_time_","complete_type_");
            for(Map f: sysFields){
                String act_id = f.get("related_act_id").toString();
                String act_prop = f.get("related_act_prop").toString();
                String field = f.get("field").toString();
                //当前环节 或 与指定环节相匹配
                if((act_id.equals("current_activity") || act_id.equals( task_def_key_))){
                    completeForm.put(field, curRow.get(act_prop));
                    curRow.put(field, curRow.get(act_prop));
                    if(act_prop.equals("task_name_")){
                        if(endEvent!=null){
                            completeForm.put(field, "已结束");
                        }
                    }
                }
            }
            //更新表
            baseDBService.updateEq(tn, completeForm, Lutils.genMap("id_", curRow.get("id_")));
            //更新日志主要action_type要为空，否则会将update的记录也修改掉。
            flowableMapper.updateunCompletedTask(Lutils.genMap("tn", tn + "_log","updateMap",completeForm, "id_", curRow.get("id_")));
            //找出需要同步的字段
            Map syncData = new HashMap();
            syncFields.stream().filter(o->completeForm.containsKey(o.get("field"))).collect(Collectors.toList()).forEach(o->{
                syncData.put(o.get("field").toString(), completeForm.get(o.get("field")));
            });
//            if(!syncData.isEmpty())
//                baseDBService.updateEq(tn, syncData, Lutils.genMap("proc_inst_id_", proc_inst_id_));
            //记录日志
//            need_log_ids.add(curRow.get("id_"));
            //删除同一用户任务类型的该用户的操作记录。
            flowableMapper.delete_old_done_task(Lutils.genMap("tn", tn, "proc_inst_id_", proc_inst_id_, "task_def_key_", completedTask.getTaskDefinitionKey()));
            //任务结束
            if(endEvent!=null){
                //找出需要同步的字段
                syncFields.stream().filter(o -> completeForm.containsKey(o.get("field"))).collect(Collectors.toList()).forEach(o -> {
                    String act_prop = StringUtils.nvl((String)o.get("related_act_prop"),"");
                    if(act_prop.equals("task_name_")){
                        syncData.put(o.get("field").toString(), StringUtils.nvl(endEvent.getActivityName(),"已完成"));
                    }
                    else{
                        syncData.put(o.get("field").toString(), completeForm.get(act_prop));
                    }
                });
                syncData.put("is_inst_ended_", true);
                baseDBService.updateEq(tn, syncData,Lutils.genMap("proc_inst_id_",proc_inst_id_));

            }
            else {
                // 该用户任务完成后，获取流转到的下一级的任务，添加到表中
                List<Task> taskList = taskService.createTaskQuery().processInstanceId(proc_inst_id_).list();
                //如果下一步没有节点，则跳过
                if (!taskList.isEmpty()) {
                    List<String> task_ids = taskList.stream().map(o -> (String) o.getId()).collect(Collectors.toList());
                    //查找已在tcdx_datatable26的task
                    List<String> exists_task_ids_ = baseDBService.selectIn(tn, "task_id_", task_ids).stream().map(m -> (String) m.get("task_id_")).collect(Collectors.toList());
                    List<Integer> new_ids = gen_ids(taskList.size());
                    for (int i = 0; i < taskList.size(); i++) {
                        Task newTask = taskList.get(i);
                        //跳过已经在datatable出现的任务
                        if (exists_task_ids_.contains(newTask.getId())) continue;
                        Map assigneeInfo = new HashMap<>(userInfo);
                        Map taskForm = new HashMap(curRow);
                        taskForm.put("id_", new_ids.get(i));
                        taskForm.put("proc_inst_id_", newTask.getProcessInstanceId());
                        taskForm.put("task_id_", newTask.getId());
                        taskForm.put("task_name_", newTask.getName());
                        taskForm.put("task_def_key_", newTask.getTaskDefinitionKey());
                        taskForm.put("execution_id_", newTask.getExecutionId());
                        taskForm.put("assignee_", assigneeInfo.get("user_name"));
                        taskForm.put("assignee_group_", assigneeInfo.get("user_group"));
                        taskForm.put("complete_user_", null);
                        taskForm.put("complete_group_", null);
                        taskForm.put("complete_time_", null);
                        taskForm.put("complete_type_", null);
                        taskForm.put("form_id_", null);
                        taskForm.put("is_done_", false);
                        taskForm.put("is_inst_user_new_complete_", false);
                        taskForm.put("is_inst_new_complete_", false);
                        taskForm.put("prev_task_id_", completedTask.getId());
                        taskForm.put("prev_task_name_", completedTask.getName());
                        taskForm.put("prev_task_def_key_", completedTask.getTaskDefinitionKey());
                        taskForm.put("parent_execution_id_", completedTask.getExecutionId());
                        taskForm.put("prev_deliver_staff_", userInfo.get("user_name"));
                        taskForm.put("prev_deliver_group_", userInfo.get("user_group"));
                        taskForm.put("prev_deliver_time_", completedTask.getEndTime());
                        taskForm.put("prev_deliver_type_", "task-complete");
                        taskForm.put("operation_order_", operation_order_ + 1);
                        //填充系统字段
                        for (Map f : sysFields) {
                            String act_id = f.get("related_act_id").toString();
                            String act_prop = f.get("related_act_prop").toString();
                            String field = f.get("field").toString();
                            //当前环节 或 与指定环节相匹配
                            if (act_id.equals("current_activity") || act_id.equals(task_def_key_)) {
                                taskForm.put(field, taskForm.get(act_prop));
                            }
                        }
                        baseDBService.insertMap(tn, taskForm);
                        //找出需要同步的字段
                        syncFields.stream().filter(o -> taskForm.containsKey(o.get("field"))).collect(Collectors.toList()).forEach(o -> {
                            syncData.put(o.get("field").toString(), taskForm.get(o.get("field")));
                        });
                        need_log_ids.add(new_ids.get(i));
                    }
                }
            }
            //实例数据同步
            if(!syncData.isEmpty())
                baseDBService.updateEq(tn, syncData, Lutils.genMap("proc_inst_id_", proc_inst_id_));
            //更新该实例的待办用户任务数
            flowableMapper.update_todo_tasks(Lutils.genMap("tn", tn, "proc_inst_id_", proc_inst_id_));
        }
        //批量保存日志，获取新添加的数据，插入日志表.
        if( need_log_ids.size() > 0 )
            flowableMapper.copy_to_log(MapUtils.G( "tn", tn, "ids", need_log_ids));
    }
     * */

    /**
     * 根据依赖表的ids所在行 关联当前表match_column的值, 与当前表match_column匹配的ids,ids即当前表要依赖更新的范围.
     * @param columnRule  当前列的操作对象ColumnRuleOperation
     * */
    public void addInIds_ByDependMatchColValues(ColumnRuleOperation columnRule){
        List<Map> dependDependFieldOldValues = baseDBService.selectIn(
                columnRule.dependTableName,
                true,
                columnRule.updateRelation.getDependMatchFields(),
                "id_",
                columnRule.dependIds);
        ///------------------------------------------------------------------------
        for (Map dependTableOldRow : dependDependFieldOldValues) {
            Map triggerTableOldMatchValue = new HashMap();
            if(Lutils.nvl(columnRule.updateRelation.match_column1,"").length()>0){
                triggerTableOldMatchValue.put(columnRule.updateRelation.match_column1, dependTableOldRow.get(columnRule.updateRelation.depend_table_match_column1));
            }
            if(Lutils.nvl(columnRule.updateRelation.match_column2,"").length()>0){
                triggerTableOldMatchValue.put(columnRule.updateRelation.match_column2, dependTableOldRow.get(columnRule.updateRelation.depend_table_match_column2));
            }
            if(Lutils.nvl(columnRule.updateRelation.match_column3,"").length()>0){
                triggerTableOldMatchValue.put(columnRule.updateRelation.match_column3, dependTableOldRow.get(columnRule.updateRelation.depend_table_match_column3));
            }
            columnRule.orWhereOfRowsList.add(triggerTableOldMatchValue);
        }
        //查匹配的行的ids
        List<Integer> inIds = baseDBService.selectByCauses(columnRule.tableName,
                Lutils.genList("id_"),
                columnRule.getWhereCause(),
                null).stream().map(o->(Integer)o.get("id_")).collect(Collectors.toList());
        columnRule.addInIds(inIds);
    }

    public void addDependIds_FromDependColumnOperations(ColumnRuleOperation upperTableColumnOperation, List<ColumnRuleOperation> dependTableColOperationList)
    {
        for (String column : upperTableColumnOperation.updateRelation.getDependFields()) {
            //根据每个关联的列，找到匹配的操作，合并操作中的where条件
            for (ColumnRuleOperation dependColumnRuleOperation : dependTableColOperationList) {
                if (column.equals(dependColumnRuleOperation.column)) {
                    upperTableColumnOperation.dependIds.addAll(dependColumnRuleOperation.inIds);
                }
            }
        }
    }
}
